<template>
  <div class="contract-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button text @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>合同详情</h2>
        <el-tag :type="getStatusColor(contractData.status)">
          {{ getStatusName(contractData.status) }}
        </el-tag>
      </div>
      <div class="header-actions">
        <el-button @click="handlePrint">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
        <el-button @click="handleDownload">
          <el-icon><Download /></el-icon>
          下载
        </el-button>
        <el-button type="primary" @click="handleEdit" v-if="canEdit">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：合同信息 -->
      <el-col :span="16">
        <!-- 基本信息 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="合同编号">{{ contractData.code }}</el-descriptions-item>
            <el-descriptions-item label="合同名称">{{ contractData.name }}</el-descriptions-item>
            <el-descriptions-item label="合同类型">
              <el-tag :type="getTypeColor(contractData.type)">
                {{ getTypeName(contractData.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="合同金额">
              <span class="amount">¥{{ formatAmount(contractData.amount) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="签订日期">{{ contractData.signDate }}</el-descriptions-item>
            <el-descriptions-item label="开始日期">{{ contractData.startDate }}</el-descriptions-item>
            <el-descriptions-item label="结束日期">
              <span :class="{ 'text-danger': isExpiringSoon }">
                {{ contractData.endDate }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="剩余天数">
              <span :class="{ 'text-danger': isExpiringSoon }">
                {{ remainingDays }} 天
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 双方信息 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>双方信息</span>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <h4>甲方信息</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="名称">{{ contractData.partyA }}</el-descriptions-item>
                <el-descriptions-item label="联系人">{{ contractData.partyAContact }}</el-descriptions-item>
                <el-descriptions-item label="电话">{{ contractData.partyAPhone }}</el-descriptions-item>
                <el-descriptions-item label="地址">{{ contractData.partyAAddress }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <h4>乙方信息</h4>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="名称">{{ contractData.partyB }}</el-descriptions-item>
                <el-descriptions-item label="联系人">{{ contractData.partyBContact }}</el-descriptions-item>
                <el-descriptions-item label="电话">{{ contractData.partyBPhone }}</el-descriptions-item>
                <el-descriptions-item label="地址">{{ contractData.partyBAddress }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>

        <!-- 合同内容 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>合同条款</span>
            </div>
          </template>

          <div class="contract-terms">
            <pre>{{ contractData.terms }}</pre>
          </div>

          <el-divider />

          <div class="contract-remark">
            <h4>备注说明</h4>
            <p>{{ contractData.remark || '无' }}</p>
          </div>
        </el-card>

        <!-- 合同附件 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>合同附件</span>
            </div>
          </template>

          <el-empty v-if="contractData.attachments.length === 0" description="暂无附件" />
          <div v-else class="attachments-list">
            <div v-for="file in contractData.attachments" :key="file.id" class="attachment-item">
              <el-icon class="file-icon"><Document /></el-icon>
              <span class="file-name">{{ file.name }}</span>
              <span class="file-size">{{ file.size }}</span>
              <el-button text type="primary" @click="handleDownloadFile(file)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 审批记录 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>审批记录</span>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
              v-for="item in approvalHistory"
              :key="item.id"
              :timestamp="item.time"
              :type="item.type"
            >
              <div class="timeline-content">
                <div class="timeline-header">
                  <strong>{{ item.user }}</strong>
                  <el-tag :type="item.statusType" size="small">{{ item.action }}</el-tag>
                </div>
                <div v-if="item.comment" class="timeline-comment">
                  {{ item.comment }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <!-- 右侧：操作记录 -->
      <el-col :span="8">
        <!-- 快速操作 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>

          <div class="quick-actions">
            <el-button type="primary" block @click="handleEdit" v-if="canEdit">
              编辑合同
            </el-button>
            <el-button type="success" block @click="handleApprove" v-if="canApprove">
              审批合同
            </el-button>
            <el-button type="warning" block @click="handleTerminate" v-if="canTerminate">
              终止合同
            </el-button>
            <el-button type="info" block @click="handleRenew" v-if="canRenew">
              续签合同
            </el-button>
          </div>
        </el-card>

        <!-- 操作日志 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>操作日志</span>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
              v-for="log in operationLogs"
              :key="log.id"
              :timestamp="log.time"
              size="small"
            >
              <div class="log-item">
                <strong>{{ log.user }}</strong>
                <span>{{ log.action }}</span>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Printer, Download, Edit, Document
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const contractId = computed(() => route.params.id)

// 合同数据
const contractData = ref({
  id: 1,
  code: 'CT2024001',
  name: '软件开发服务合同',
  type: 'service',
  status: 'active',
  amount: 500000,
  signDate: '2024-01-15',
  startDate: '2024-02-01',
  endDate: '2024-12-31',
  partyA: '某科技有限公司',
  partyAContact: '张三',
  partyAPhone: '13800138000',
  partyAAddress: '北京市朝阳区XX路XX号',
  partyB: '某信息技术公司',
  partyBContact: '李四',
  partyBPhone: '13900139000',
  partyBAddress: '上海市浦东新区XX路XX号',
  terms: '1. 甲方委托乙方进行软件开发项目\n2. 项目周期为10个月，自2024年2月1日至2024年12月31日\n3. 合同总金额为人民币50万元\n4. 付款方式：\n   - 首付款（30%）：签约后7个工作日内支付\n   - 中期款（40%）：项目完成50%后支付\n   - 尾款（30%）：项目验收合格后支付\n5. 知识产权归甲方所有\n6. 保密条款：双方应对合同内容及项目信息保密\n7. 违约责任：任何一方违约需承担相应责任\n8. 争议解决：通过友好协商解决，协商不成提交仲裁',
  remark: '本合同一式两份，甲乙双方各执一份，具有同等法律效力',
  attachments: [
    { id: 1, name: '合同正本.pdf', size: '2.3 MB' },
    { id: 2, name: '附件1-项目计划书.docx', size: '1.5 MB' }
  ]
})

// 审批记录
const approvalHistory = ref([
  {
    id: 1,
    user: '张三 - 部门经理',
    action: '已通过',
    type: 'success',
    statusType: 'success',
    time: '2024-01-16 10:30',
    comment: '同意签订此合同'
  },
  {
    id: 2,
    user: '李四 - 财务经理',
    action: '已通过',
    type: 'success',
    statusType: 'success',
    time: '2024-01-16 14:20',
    comment: '预算充足，同意'
  },
  {
    id: 3,
    user: '王五 - 总经理',
    action: '已通过',
    type: 'success',
    statusType: 'success',
    time: '2024-01-16 16:45',
    comment: '批准'
  }
])

// 操作日志
const operationLogs = ref([
  { id: 1, user: '张三', action: '创建了合同', time: '2024-01-15 09:00' },
  { id: 2, user: '张三', action: '提交审批', time: '2024-01-15 09:30' },
  { id: 3, user: '李四', action: '审批通过', time: '2024-01-16 14:20' },
  { id: 4, user: '王五', action: '审批通过', time: '2024-01-16 16:45' },
  { id: 5, user: '系统', action: '合同生效', time: '2024-02-01 00:00' }
])

// 计算属性
const remainingDays = computed(() => {
  const end = new Date(contractData.value.endDate)
  const now = new Date()
  const days = Math.ceil((end - now) / (1000 * 60 * 60 * 24))
  return days > 0 ? days : 0
})

const isExpiringSoon = computed(() => {
  return remainingDays.value <= 30 && remainingDays.value > 0
})

const canEdit = computed(() => {
  return ['draft', 'rejected'].includes(contractData.value.status)
})

const canApprove = computed(() => {
  return contractData.value.status === 'pending'
})

const canTerminate = computed(() => {
  return contractData.value.status === 'active'
})

const canRenew = computed(() => {
  return ['active', 'completed'].includes(contractData.value.status) && remainingDays.value <= 60
})

// 工具函数
const formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 })
}

const getTypeName = (type) => {
  const typeMap = {
    sales: '销售合同',
    purchase: '采购合同',
    service: '服务合同',
    lease: '租赁合同',
    other: '其他'
  }
  return typeMap[type] || type
}

const getTypeColor = (type) => {
  const colorMap = {
    sales: 'success',
    purchase: 'warning',
    service: 'primary',
    lease: 'info',
    other: ''
  }
  return colorMap[type] || ''
}

const getStatusName = (status) => {
  const statusMap = {
    draft: '草稿',
    pending: '待审批',
    approved: '已通过',
    rejected: '已驳回',
    active: '执行中',
    completed: '已完成',
    terminated: '已终止'
  }
  return statusMap[status] || status
}

const getStatusColor = (status) => {
  const colorMap = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    active: 'primary',
    completed: '',
    terminated: 'danger'
  }
  return colorMap[status] || ''
}

// 操作方法
const handleBack = () => {
  router.back()
}

const handlePrint = () => {
  window.print()
}

const handleDownload = () => {
  ElMessage.success('正在下载合同...')
}

const handleDownloadFile = (file) => {
  ElMessage.success(`正在下载 ${file.name}`)
}

const handleEdit = () => {
  router.push(`/contract/edit/${contractId.value}`)
}

const handleApprove = () => {
  router.push(`/contract/approval?id=${contractId.value}`)
}

const handleTerminate = () => {
  ElMessageBox.prompt('请输入终止原因', '终止合同', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '请输入终止原因'
  }).then(({ value }) => {
    ElMessage.success('合同已终止')
  })
}

const handleRenew = () => {
  ElMessage.info('续签功能开发中')
}

onMounted(() => {
  // 加载合同详情
  console.log('加载合同详情', contractId.value)
})
</script>

<style scoped>
.contract-detail-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.amount {
  font-size: 16px;
  font-weight: 600;
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
  font-weight: 600;
}

.contract-terms pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  line-height: 1.8;
  color: #606266;
}

.contract-remark h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.contract-remark p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.attachments-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.file-icon {
  font-size: 24px;
  color: #409eff;
}

.file-name {
  flex: 1;
  color: #303133;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.timeline-content {
  padding-left: 10px;
}

.timeline-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.timeline-comment {
  color: #606266;
  font-size: 14px;
  margin-top: 5px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.log-item {
  font-size: 14px;
  color: #606266;
}

.log-item strong {
  color: #303133;
  margin-right: 5px;
}

@media print {
  .page-header,
  .quick-actions {
    display: none;
  }
}
</style>

